import wx, os, shutil, sys, time, datetime
import urllib2
from  urllib2 import urlopen
import pygame
from pygame.locals import *
from pygame.font import *
from datetime import datetime, date

# The following line is a solution to the problem
# "pygame.error: No available video device"
# but might cause problems for other users
os.environ['SDL_VIDEODRIVER'] = 'windib'


global pics_hor; pics_hor = 500
global pics_ver; pics_ver = 500
global BLACK; BLACK = (0, 0, 0)
global WHITE; WHITE = (255, 255, 255)
global RED; RED = (255, 0, 0)
global GREEN; GREEN = (0, 255, 0)
global BLUE; BLUE = (0, 0, 255)
global GREY; GREY = (100, 100, 100)
global G_BROWN_1; G_BROWN_1 = (193, 153, 57)
global G_BROWN_2; G_BROWN_2 = (255, 224, 155)

global pygame_events_on
global px, py, xpos, ypos, zoom, pxz, pyz
px=500 # map x-size in pixels
py=500 # map y-size in pixels
xpos=0 # x-offset for drawing the map
ypos=0 # y-offset for drawing the map
zoom=1
pxz = px/zoom
pyz = py/zoom


#-------------------------------------------------------------------------------
# Here the main user interface window is created
#-------------------------------------------------------------------------------

class Menu(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title='Grepotools', pos = (0,0), size=(500, 720))

        #-----------------------------------------------------------------------
        # Creating the menu
        #-----------------------------------------------------------------------

        # load the URLs from the config file
        LoadConfigData()
        self.MakeWorldMap()

        # Create the panel to put the widgets on
        panel = wx.Panel(self)
        panel.SetBackgroundColour(G_BROWN_1)

        # Create a menu bar with a file menu and a map menu
        menubar = wx.MenuBar()
        file = wx.Menu()
        map = wx.Menu()
        
        # Define the choices for the file menu
        Fetch_data = wx.MenuItem(file, 1, '&Download world data\tCtrl+F')
        file.AppendItem(Fetch_data)
        Load_data = wx.MenuItem(file, 2, '&Load world data\tCtrl+L')
        file.AppendItem(Load_data)
        quit = wx.MenuItem(file, 3, '&Quit\tCtrl+Q')
        file.AppendItem(quit)

        # Define the choices for the map menu
        Show_map = wx.MenuItem(map, 4, '&Show/reset map\tCtrl+M')
        map.AppendItem(Show_map)
        Draw_cities = wx.MenuItem(map, 6, '&Draw cities\tCtrl+C')
        map.AppendItem(Draw_cities)
        Draw_conquers = wx.MenuItem(map, 9, '&Show conquers\tCtrl+C')
        map.AppendItem(Draw_conquers)
        Save_Map = wx.MenuItem(map, 8, '&Save map\tCtrl+S')
        map.AppendItem(Save_Map)
        testbutton = wx.MenuItem(map, 7, '&testbutton\tCtrl+C')
        map.AppendItem(testbutton)

        # Link the choices to the def routines
        self.Bind(wx.EVT_MENU, self.OnFetchData, id=1)
        self.Bind(wx.EVT_MENU, self.OnLoadData, id=2)
        self.Bind(wx.EVT_MENU, self.OnQuit, id=3)
        self.Bind(wx.EVT_MENU, self.OnShowMap, id=4)
        self.Bind(wx.EVT_MENU, self.OnDrawCities, id=6)
        self.Bind(wx.EVT_MENU, Ontestbutton, id=7)
        self.Bind(wx.EVT_MENU, self.OnSaveMap, id=8)
        self.Bind(wx.EVT_MENU, self.OnShowConquers, id=9)
         
        # Add the menus to the menu bar
        menubar.Append(file, '&File')
        menubar.Append(map, '&Map')

        # add the menu bar to the window
        self.SetMenuBar(menubar)
        self.statusbar = self.CreateStatusBar()
        
        #-----------------------------------------------------------------------
        # Creating player data section
        #-----------------------------------------------------------------------
        box1=wx.StaticBox(panel, -1, 'World data', pos=(5, 3), size=(150, 140))
        
        # Create the text labels and widgets on the interface window
        self.aw = aw
        world_label = wx.StaticText(panel, -1, 'World: ', (10, 20))
        self.world_box = wx.ComboBox(panel, -1, str(world[aw]), pos=(50, 17), size=(100, 10), name = 'World')
        self.world_box.SetBackgroundColour(G_BROWN_2)
        for w in range(0, len(world)):
            self.world_box.Append(world[w])
            
        players = "No data"
        self.players_text = wx.StaticText(panel, -1, players, (80, 40), (60,20))
        self.players_label = wx.StaticText(panel, -1, "Players:", (10, 40))
        
        alliances = "No data"
        self.alliances_text = wx.StaticText(panel, -1, alliances, (80, 60), (60,20))
        self.alliances_label = wx.StaticText(panel, -1, "Alliances:", (10, 60))

        cities = "No data"
        self.cities_text = wx.StaticText(panel, -1, cities, (80, 80), (60,20))
        self.cities_label = wx.StaticText(panel, -1, "Cities:", (10, 80))

        islands = "No data"
        self.islands_text = wx.StaticText(panel, -1, islands, (80, 100), (60,20))
        self.islands_label = wx.StaticText(panel, -1, "Islands:", (10, 100))

        conquers = "No data"
        self.conquers_text = wx.StaticText(panel, -1, conquers, (80, 120), (60,20))
        self.conquers_label = wx.StaticText(panel, -1, "Conquers:", (10, 120))

        #-----------------------------------------------------------------------
        # Creating the conquer map section
        #-----------------------------------------------------------------------
       
        box2=wx.StaticBox(panel, -1, 'Conquer Map', pos=(165, 3), size=(150, 140))
        date_start_text = wx.StaticText(panel, -1, 'Select first date', (180,22), (100,20))
        self.start_date=wx.DatePickerCtrl(panel, -1, size=(120, -1), pos=(180,40), 
                                          style=wx.DP_DROPDOWN | wx.DP_SHOWCENTURY)

        date_end_text = wx.StaticText(panel, -1, 'Select last date', (180,62), (100,20))
        self.end_date=wx.DatePickerCtrl(panel, -1, size=(120, -1), pos=(180,80), 
                                        style=wx.DP_DROPDOWN | wx.DP_SHOWCENTURY)

        self.ok_button=wx.Button(panel, -1, "show conquers", pos=(193, 110))
        self.ok_button.SetBackgroundColour(G_BROWN_2)
        self.Bind(wx.EVT_BUTTON, self.OnShowConquers, self.ok_button)

        #-----------------------------------------------------------------------
        # Creating the listbox section
        #-----------------------------------------------------------------------

        # alliance listbox
        
        box3=wx.StaticBox(panel, -1, 'Alliances', pos=(5, 150), size=(150, 480))
        self.ally_listbox = wx.ListBox(panel, -1, pos=(10, 170), size=(140, 270))
        self.ally_listbox.SetBackgroundColour(G_BROWN_2)
        self.ally_filter = wx.TextCtrl(panel, -1, "", pos=(10, 460), size=(140, 20))
        self.filter_ally = wx.Button(panel, -1, "Filter alliances", pos=(10, 480), size=(140, 20))
        self.filter_ally.SetBackgroundColour(G_BROWN_2)
        self.draw_ally = wx.Button(panel, -1, "Draw alliance", pos=(10, 500), size=(140, 20))
        self.draw_ally.SetBackgroundColour(G_BROWN_2)
        self.copy_players = wx.Button(panel, -1, "Copy players to listbox", pos=(10, 520), size=(140, 20))
        self.copy_players.SetBackgroundColour(G_BROWN_2)
        self.copy_players_to_clipboard = wx.Button(panel, -1, "Copy players to clipboard", pos=(10, 540), size=(140, 20))
        self.copy_players_to_clipboard.SetBackgroundColour(G_BROWN_2)

        self.ally_filter.Bind(wx.EVT_SET_FOCUS, self.OnGetFocus)
        self.ally_filter.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
        self.Bind(wx.EVT_BUTTON, self.OnFilterAlly, self.filter_ally)
        self.Bind(wx.EVT_BUTTON, self.OnDrawAlly, self.draw_ally)
        self.Bind(wx.EVT_BUTTON, self.OnCopyPlayers, self.copy_players)
        self.Bind(wx.EVT_BUTTON, self.OnCopyPlayersToClipboard, self.copy_players_to_clipboard)
        
        # player listbox
        
        box3=wx.StaticBox(panel, -1, 'Players', pos=(165, 150), size=(150, 480))        
        self.player_listbox = wx.ListBox(panel, -1, pos=(170, 170), size=(140, 270))
        self.player_listbox.SetBackgroundColour(G_BROWN_2)
        self.player_filter = wx.TextCtrl(panel, -1, "", pos=(170, 460), size=(140, 20))
        self.filter_player = wx.Button(panel, -1, "Filter players", pos=(170, 480), size=(140, 20))
        self.filter_player.SetBackgroundColour(G_BROWN_2)
        self.draw_player = wx.Button(panel, -1, "Draw player", pos=(170, 500), size=(140, 20))
        self.draw_player.SetBackgroundColour(G_BROWN_2)
        self.copy_cities = wx.Button(panel, -1, "Copy cities to listbox", pos=(170, 520), size=(140, 20))
        self.copy_cities.SetBackgroundColour(G_BROWN_2)
        self.copy_cities_to_clipboard = wx.Button(panel, -1, "Copy cities to clipboard", pos=(170, 540), size=(140, 20))
        self.copy_cities_to_clipboard.SetBackgroundColour(G_BROWN_2)
       
        self.player_filter.Bind(wx.EVT_SET_FOCUS, self.OnGetFocus)
        self.player_filter.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
        self.Bind(wx.EVT_COMBOBOX, self.OnSelectWorld, self.world_box)
        self.Bind(wx.EVT_BUTTON, self.OnFilterPlayer, self.filter_player)
        self.Bind(wx.EVT_BUTTON, self.OnDrawPlayer, self.draw_player)
        self.Bind(wx.EVT_BUTTON, self.OnCopyCities, self.copy_cities)
        self.Bind(wx.EVT_BUTTON, self.OnCopyCitiesToClipboard, self.copy_cities_to_clipboard)
        
        
        # cities listbox
        
        box3=wx.StaticBox(panel, -1, 'Cities', pos=(325, 150), size=(150, 480))
        self.cities_listbox = wx.ListBox(panel, -1, pos=(330, 170), size=(140, 270))
        self.cities_listbox.SetBackgroundColour(G_BROWN_2)
        self.cities_filter = wx.TextCtrl(panel, -1, "", pos=(330, 460), size=(140, 20))
        self.filter_cities = wx.Button(panel, -1, "Filter cities", pos=(330, 480), size=(140, 20))
        self.filter_cities.SetBackgroundColour(G_BROWN_2)
        self.draw_cities = wx.Button(panel, -1, "Draw city", pos=(330, 500), size=(140, 20))
        self.draw_cities.SetBackgroundColour(G_BROWN_2)
 
        self.cities_filter.Bind(wx.EVT_SET_FOCUS, self.OnGetFocus)
        self.cities_filter.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
        self.Bind(wx.EVT_BUTTON, self.OnFilterCities, self.filter_cities)
        self.Bind(wx.EVT_BUTTON, self.OnDrawCity, self.draw_cities)
        
        #self.OnLoadData(self)
        
        
        # Present the window
        self.Show(True)
        self.OnShowMap(True)
        
#-------------------------------------------------------------------------------
# The following routines are needed to make pygame and wxpython work together.
# Pygame has the focus most of the time, but when the user wants to enter data
# the focus is set to the widget that the player wants to use.
# By setting the pygame_events_on flag to 0 the pygame event loop is terminated
# allowing the user to enter data.
# When the widget loses focus the control is returned to the routine that
# handles pygame events
#-------------------------------------------------------------------------------

        
        
    def OnGetFocus(self, event):
        global pygame_events_on
        pygame_events_on=0
        
    def OnKillFocus(self, event):
        global pygame_events_on
        pygame_events_on=1
        self.OnShowMap(self)

        
#-------------------------------------------------------------------------------
# The following routine downloads the world data from internet
# The data is saved to a \data directory that is created if not exist
# the filename tells the world and the data stored in it
# This is done because it is not possible to make subdirectories because
# of the escape behaviour of the "\" character.
# the self.aw variable contains the currently selected world (0 = world alfa)
#-------------------------------------------------------------------------------


    def OnFetchData(self, event):
      
        self.datadir = "data"
        if not (os.path.isdir(self.datadir)):        
            os.mkdir(self.datadir)
        
        self.players_text.SetLabel("Downloading...")
        req = urllib2.urlopen(url_players[self.aw])
        players = req.read()
        fn = r'data\world_' + world[self.aw]+ '_players.txt'
        f = open(fn, 'w')
        f.write(players)
        f.close()
        self.players_text.SetLabel("Done")
        
        self.alliances_text.SetLabel("Downloading...")        
        req = urllib2.urlopen(url_alliances[self.aw])
        alliances = req.read()
        fn = r'data\world_' + world[self.aw]+ '_alliances.txt'
        f = open(fn, 'w')
        f.write(alliances)
        f.close()
        self.alliances_text.SetLabel("Done")
        
        self.cities_text.SetLabel("Downloading...")
        req = urllib2.urlopen(url_towns[self.aw])
        towns = req.read()
        fn = r'data\world_' + world[self.aw]+ '_towns.txt'
        f = open(fn, 'w')
        f.write(towns)
        f.close()
        self.cities_text.SetLabel("Done")
        
        self.islands_text.SetLabel("Downloading...")
        req = urllib2.urlopen(url_islands[self.aw])
        islands = req.read()
        fn = r'data\world_' + world[self.aw]+ '_islands.txt'
        f = open(fn, 'w')
        f.write(islands)
        f.close()
        self.islands_text.SetLabel("Done")
        
        self.conquers_text.SetLabel("Downloading...")
        req = urllib2.urlopen(url_conquers[self.aw])
        conquers = req.read()
        fn = r'data\world_' + world[self.aw]+ '_conquers.txt'
        f = open(fn, 'w')
        f.write(conquers)
        f.close()
        self.conquers_text.SetLabel("Done")
        
        # now load the data
        self.OnLoadData(0)
#-------------------------------------------------------------------------------
# The following routine loads the world data from the data files
# These data are stored in global arrays which are defined in the routine
# For players and alliances the data is appended to the respective listbox
#-------------------------------------------------------------------------------

    def OnLoadData(self, event):

        #----------------
        # Load player data
        #----------------
        
        global player_ID; player_ID = []
        global player_name; player_name = []
        global player_alliance_ID; player_alliance_ID = []
        global player_points; player_points = []
        global player_rank; player_rank = []
        global player_cities; player_cities = []

        fn = r'data\world_' + world[self.aw]+ '_players.txt'
        if not (os.path.isfile(fn)):
            dlg = wx.MessageDialog(None, "No data available for world "+ world[self.aw], caption="No Data Available", style = wx.OK) 
            dlg.ShowModal()
            return
        
        f = open(fn, 'r')
        self.players_text.SetLabel("Loading...")
        x = 0
        player = f.readline()
        while (len(player) > 0):
            k1 = player.find(',')
            k2 = player.find(',', k1+1)
            k3 = player.find(',', k2+1)
            k4 = player.find(',', k3+1)
            k5 = player.find(',', k4+1)
            player_ID.append(player[0:k1])
            player_name.append(player[k1+1:k2]) 
            player_alliance_ID.append(player[k2+1:k3]) 
            player_points.append(player[k3+1:k4]) 
            player_rank.append(player[k4+1:k5]) 
            player_cities.append(player[k5+1:len(player)-1])
            x+=1
            player = f.readline()
        f.close()

        for x in range(1, len(player_ID)):
            self.player_listbox.Append(str(player_name[x]))
        self.players_text.SetLabel(str(len(player_ID)))
        
        #----------------
        # Load alliance data
        #----------------

        global alliance_ID; alliance_ID = []
        global alliance_name; alliance_name = []
        global alliance_points; alliance_points = []
        global alliance_rank; alliance_rank = []
        global alliance_cities; alliance_cities = []
        global alliance_members; alliance_members = []

        fn = r'data\world_' + world[self.aw]+ '_alliances.txt'
        f = open(fn, 'r')
        x = 0
        alliance = f.readline()
        while (len(alliance) > 0):
            k1 = alliance.find(',')
            k2 = alliance.find(',', k1+1)
            k3 = alliance.find(',', k2+1)
            k4 = alliance.find(',', k3+1)
            k5 = alliance.find(',', k4+1)
            alliance_ID.append(alliance[0:k1])
            alliance_name.append(alliance[k1+1:k2]) 
            alliance_points.append(alliance[k2+1:k3]) 
            alliance_cities.append(alliance[k3+1:k4]) 
            alliance_members.append(alliance[k4+1:k5])
            alliance_rank.append(alliance[k5+1:len(alliance)-1]) 
            x+=1
            alliance = f.readline()
        f.close()

        for x in range(0,len(alliance_ID)):
            self.ally_listbox.Append(str(alliance_name[x]))
        self.alliances_text.SetLabel(str(len(alliance_ID)))

        #----------------
        # Load city data
        #----------------

        global town_ID; town_ID = []
        global town_player; town_player = []
        global town_name; town_name = []
        global town_island_x; town_island_x = []
        global town_island_y; town_island_y = []
        global town_island_number; town_island_number = []
        global town_points; town_points = []

        fn = r'data\world_' + world[self.aw]+ '_towns.txt'
        f = open(fn, 'r')
        self.cities_text.SetLabel("Loading...")
        x = 0
        town = f.readline()
        while (len(town) > 0):
            k1 = town.find(',')
            k2 = town.find(',', k1+1)
            k3 = town.find(',', k2+1)
            k4 = town.find(',', k3+1)
            k5 = town.find(',', k4+1)
            k6 = town.find(',', k5+1)
            town_ID.append(town[0:k1])
            town_player.append(town[k1+1:k2])
            town_name.append(town[k2+1:k3]) 
            town_island_x.append(town[k3+1:k4]) 
            town_island_y.append(town[k4+1:k5])
            town_island_number.append(town[k5+1:k6])
            town_points.append(town[k6+1:len(town)-1]) 
            x+=1
            town = f.readline()
        f.close()
        self.cities_text.SetLabel(str(len(town_ID)))
        
        #----------------
        # Load island data
        #----------------

        global island_ID; island_ID = []
        global island_x; island_x = []
        global island_y; island_y = []
        global island_number; island_number = []
        global island_color; island_color = []

        fn = r'data\world_' + world[self.aw]+ '_islands.txt'
        f = open(fn, 'r')
        self.islands_text.SetLabel("Loading...")
        x = 0
        island = f.readline()
        while (len(island) > 0):
            k1 = island.find(',')
            k2 = island.find(',', k1+1)
            k3 = island.find(',', k2+1)
            k4 = island.find(',', k3+1)
            island_ID.append(island[0:k1])
            island_x.append(island[k1+1:k2]) 
            island_y.append(island[k2+1:k3])
            island_number.append(island[k3+1:k4])
            x+=1
            island = f.readline()
        f.close()
        self.islands_text.SetLabel(str(len(island_ID)))

        #----------------
        # Load conquer data
        #----------------

        global conquer_town_ID; conquer_town_ID = []
        global conquer_time; conquer_time = []
        global conquer_new_player_ID; conquer_new_player_ID = []
        global conquer_old_player_ID; conquer_old_player_ID = []
        global conquer_new_ally_ID; conquer_new_ally_ID = []
        global conquer_old_ally_ID; conquer_old_ally_ID = []
        global conquer_town_points; conquer_town_points = []
        
        fn = r'data\world_' + world[self.aw]+ '_conquers.txt'
        f = open(fn, 'r')
        self.conquers_text.SetLabel("Loading...")
        x = 0
        conquer = f.readline()
        while (len(conquer) > 0):
            k1 = conquer.find(',')
            k2 = conquer.find(',', k1+1)
            k3 = conquer.find(',', k2+1)
            k4 = conquer.find(',', k3+1)
            k5 = conquer.find(',', k4+1)
            k6 = conquer.find(',', k5+1)
            conquer_town_ID.append(conquer[0:k1])
            conquer_time.append(conquer[k1+1:k2]) 
            conquer_new_player_ID.append(conquer[k2+1:k3]) 
            conquer_old_player_ID.append(conquer[k3+1:k4]) 
            conquer_new_ally_ID.append(conquer[k4+1:k5]) 
            conquer_old_ally_ID.append(conquer[k5+1:k6]) 
            conquer_town_points.append(conquer[k6+1:len(conquer)-1])
            x+=1
            conquer = f.readline()
        f.close()
        self.conquers_text.SetLabel(str(len(conquer_town_ID)))

#-------------------------------------------------------------------------------
# The following routines are initiated by pressing the filter button
# The string entered in the text input field is collected
# then the names containing the string are appended to the listbox
#-------------------------------------------------------------------------------

    def OnFilterPlayer(self, event):
        self.player_listbox.Clear()
        s = self.player_filter.GetValue()
        for x in range (0, len(player_ID)):
            if s in player_name[x]:
                self.player_listbox.Append(str(player_name[x]))

    def OnFilterAlly(self, event):
        self.ally_listbox.Clear()
        s = self.ally_filter.GetValue()
        for x in range (0, len(alliance_ID)):
            if s in alliance_name[x]:
                self.ally_listbox.Append(str(alliance_name[x]))

    def OnFilterCities(self, event):
        self.cities_listbox.Clear()
        s = self.cities_filter.GetValue()
        for x in range (0, len(town_ID)):
            if s in town_name[x]:
                self.cities_listbox.Append(str(town_name[x]))

    def OnCopyPlayers(self, event):
        alliance_name =  self.ally_listbox.GetStringSelection()
        alliance = get_alliance_ID(alliance_name)
        self.player_listbox.Clear()
        for player in range(0, len(player_ID)):
            if (str(player_alliance_ID[player]) == str(alliance)):
                self.player_listbox.Append(str(player_name[player]))

    def OnCopyCities(self, event):
        player_name =  self.player_listbox.GetStringSelection()
        player = get_player_ID(player_name)
        self.cities_listbox.Clear()
        for city in range(0, len(town_ID)):
          #  print str(town_player[city]), str(player)
            if (str(town_player[city]) == str(player)):
                self.cities_listbox.Append(str(town_name[city]))

                
    def OnCopyPlayersToClipboard(self, event):
        alliance_name =  self.ally_listbox.GetStringSelection()
        alliance = get_alliance_ID(alliance_name)
        ct=''
        for player in range(0, len(player_ID)):
            if (str(player_alliance_ID[player]) == str(alliance)):
                ct=ct + '[player]'+(str(player_name[player]))+'[/player]\n'
        CopyToClipboard(ct)
        
     
    def OnCopyCitiesToClipboard(self, event):
        player_name =  self.player_listbox.GetStringSelection()
        player = get_player_ID(player_name)
        ct=''
        for city in range(0, len(town_ID)):
            if (str(town_player[city]) == str(player)):
                ct=ct + '[town]'+(str(town_ID[city]))+'[/town]\n'
        CopyToClipboard(ct)
        
                
#-------------------------------------------------------------------------------
# The following toutines are initiated by pressing the draw button
# The selected name is collected, then the corresponding ID is searched for
# For one player the towns are checked and drawn if belonging to the player
# For an alliance the players are checked and drawn if belonging to the alliance
#-------------------------------------------------------------------------------

    def OnDrawCity(self, event):
        city_name = self.cities_listbox.GetStringSelection()
        t = town_name.index(city_name)
        color = choose_colour()
        x = int(town_island_x[t])
        y = int(town_island_y[t])
        self.draw_town(x, y, color, 'big')

        # Done drawing, now handle control to pygame        
        pygame_events_on=1
        self.Handle_Pygame_Events(self)

    def OnDrawPlayer(self, event):
        player_name = self.player_listbox.GetStringSelection()
        player = get_player_ID(player_name)
        color = choose_colour()
        for town in range(0, len(town_ID)):
            if (town_player[town] == player):
                x = int(town_island_x[town])
                y = int(town_island_y[town])
                self.draw_town(x, y, color, 'big')

        # Done drawing, now handle control to pygame        
        pygame_events_on=1
        self.Handle_Pygame_Events(self)

         
    def OnDrawAlly(self, event):
        alliance_name =  self.ally_listbox.GetStringSelection()
        alliance = get_alliance_ID(alliance_name)
        color = choose_colour()
        for player in range(0, len(player_ID)):
            if (str(player_alliance_ID[player]) == str(alliance)):
                for town in range(0, len(town_ID)):
                    if (town_player[town] == player_ID[player]):
                        x = int(town_island_x[town])
                        y = int(town_island_y[town])
                        self.draw_town(x, y, color, 'big')

        # Done drawing, now handle control to pygame        
        pygame_events_on=1
        self.Handle_Pygame_Events(self)
 

    def OnShowConquers(self, event):
       
        date_start = get_date(self.start_date.GetValue())
        date_end = get_date(self.end_date.GetValue())
        
        mark = pygame.image.load("mark2.tga").convert_alpha()
        print 'start date' + str(date_start)
        print 'end date' + str(date_end)
        for i in range(0, len(conquer_town_ID)):
            d=datetime.fromtimestamp(float(conquer_time[i]))
            date = d.date()
            if (date > date_start and date < date_end and len(conquer_old_player_ID[i])>1):
                c = conquer_town_ID[i]
                if c in town_ID:
                    t = town_ID.index(c)
                    x = int(town_island_x[t])
                    y = int(town_island_y[t])
                    name = town_name[t]
                    player = get_player_name(town_player[t])
                    self.worldmap.blit(mark, (x-5, y-5))

        # Done drawing, now handle control to pygame        
        pygame_events_on=1
        self.Handle_Pygame_Events(self)


    
    
#-------------------------------------------------------------------------------
# This routine is initiated when another world is selected in the drop-down box
#-------------------------------------------------------------------------------

    def OnSelectWorld(self, event):
        self.aw = self.world_box.GetSelection()
        
#-------------------------------------------------------------------------------
# This routine is selected when quit is selected from the menu bar
#-------------------------------------------------------------------------------

    def OnQuit(self, event):
        pygame.quit()
        self.Close()        

#-------------------------------------------------------------------------------
# This routine is selected when the show map is selected from the menu bar
# A pygame surface withis created which opens in a new window
#-------------------------------------------------------------------------------
        
    def OnShowMap(self, event):
        
#    os.environ['SDL_VIDEO_WINDOW_POS'] = ('5,20') # this positions the map screen top left.
        self.windowSurface = pygame.display.set_mode((px, py), RESIZABLE, 32)
        pygame.display.set_caption('Grepolis world map')
        self.windowSurface.fill(BLACK)
        self.windowSurface.blit(self.worldmap, dest=(0,0) , area=(xpos, ypos, px, py))
        pygame.display.update()
        self.Handle_Pygame_Events(self)

    def Handle_Pygame_Events(self, event):
        global pygame_events_on
        global px, py, xpos, ypos, zoom, pxz, pyz
        pygame_events_on = 1 # handle pygame events
        move_screen=0        # dont move the screen
        redraw=1             # redraw the screen on first pass
        self.statusbar.SetStatusText('Handling pygame events on')
        while pygame_events_on:
            pygame.time.wait(10) # snooze a little to spare processor time
            for action in  pygame.event.get():

                if action.type == QUIT:    # User want to leave pygame control
                    pygame.display.quit()
                    pygame_events_on=0
                    
                if action.type== VIDEORESIZE:  # window screen was resized
                    px = action.w
                    py = action.h
                    zoom = 1
                    redraw=1
                    
                if action.type == MOUSEMOTION:  # mouse movenemt detected
                    if move_screen==1:          # map movement required?
                        mouse_x = action.rel[0]
                        mouse_y = action.rel[1]
                        xpos=xpos-mouse_x       # calculate new position
                        ypos=ypos-mouse_y
                        pxz = int(px/zoom)
                        pyz = int(py/zoom)
                        if (xpos<0):            # dont leave the map area
                            xpos=0
                        if (ypos<0):
                            ypos=0
                        if (xpos+pxz>1000):
                            xpos=1000-pxz
                        if (ypos+pyz>1000):
                            ypos=1000-pyz

                    # In order to zoom the part of the worldmap the user wants to see
                    # is copied to a temporary surface, next the surface is scaled
                    # and copied to the window surface
                            
                    self.tempmap=pygame.Surface((px/zoom, py/zoom))
                    self.tempmap.blit(self.worldmap, dest=(0,0) , area=(xpos, ypos, int(px/zoom), int(py/zoom)))
                    pygame.transform.smoothscale(self.tempmap, (px, py), self.windowSurface)
                    pygame.display.update()
                    redraw=0
                    
                if action.type == MOUSEBUTTONDOWN:  # left mouse button pressed
                    mouse_button = action.button
                    if mouse_button == 1:
                        move_screen=1
                        
                if action.type == MOUSEBUTTONUP:    # finished pressing left mouse button
                    move_screen=0

                if action.type == KEYDOWN:
                    
                    if (action.key == K_UP):     # Calculate new zoom factor
                        zoom = zoom + 0.05
                        redraw=1    
    
                    if (action.key == K_DOWN):
                        zoom = zoom - 0.05
                        redraw=1

                # Dont redraw the window surface when not needed because
                # the display_set_mode command causes a mouse-up event
                # which messes-up the scrolling of the window.
                  
                if(redraw==1):
                    self.windowSurface = pygame.display.set_mode((px, py), RESIZABLE)
                    self.tempmap=pygame.Surface((px/zoom, py/zoom))
                    self.tempmap.blit(self.worldmap, dest=(0,0) , area=(xpos, ypos, int(px/zoom), int(py/zoom)))
                    pygame.transform.smoothscale(self.tempmap, (px, py), self.windowSurface)
                    pygame.display.update()
                    redraw=0
        self.statusbar.SetStatusText('Handling pygame events off')


#-------------------------------------------------------------------------------
# This routine makes a 1000x1000 world map that is NOT presented to the user
# This is the original world-size map
# It also draws the grid and places ocean numbers on the map
#-------------------------------------------------------------------------------
        
    def MakeWorldMap(self):
        f=pygame.font.init()
        self.worldmap = pygame.Surface((1000, 1000))

        for i in range(1,11):
            pygame.draw.line(self.worldmap, (125, 125, 125), (100*i, 0), (100*i, 1000), 1)
            pygame.draw.line(self.worldmap, (125, 125, 125), (0, 100*i), (1000, 100*i), 1)
            self.show_text(str((i*10)-10), 100*(i-1)+2, 2, WHITE)
            self.show_text(str(i-1), 990, 100*(i-1)+2, WHITE)
       
#-------------------------------------------------------------------------------
# The following routine displays a text on the world map
#-------------------------------------------------------------------------------

    def show_text(self, t, x, y, color):

        basicFont = pygame.font.Font("freesansbold.ttf", 20)
        text = basicFont.render(t, True, color, BLACK)
        textRect = text.get_rect()
        textRect.top = y
        textRect.left = x
        self.worldmap.blit(text, textRect)

#-------------------------------------------------------------------------------
# This routine draws all cities in the towns array
#-------------------------------------------------------------------------------

    def OnDrawCities(self, event):
        for i in range(0, len(town_ID)):
            x = int(town_island_x[i])
            y = int(town_island_y[i])
            self.draw_town(x, y, GREY, 'small')

        # Done drawing, now handle control to pygame        

        pygame_events_on=1
        self.Handle_Pygame_Events(self)


#-------------------------------------------------------------------------------
# The following routine draws one single town on the map
# The town is made of 4 (small) or 8 (big) pixels
#-------------------------------------------------------------------------------

    def draw_town(self, x, y, c, size):                  

        self.worldmap.set_at((x, y), c)
        self.worldmap.set_at((x+1, y), c)
        self.worldmap.set_at((x-1, y), c)
        self.worldmap.set_at((x, y+1), c)
        self.worldmap.set_at((x, y-1), c)
    
        if (size == 'big'):
            self.worldmap.set_at((x+1, y+1), c)
            self.worldmap.set_at((x+1, y-1), c)
            self.worldmap.set_at((x-1, y+1), c)
            self.worldmap.set_at((x-1, y-1), c)

#-------------------------------------------------------------------------------
# This routine saves the map as presented on the windowsurface
#-------------------------------------------------------------------------------

    def OnSaveMap(self, event):
        dialog = wx.FileDialog(None, "Enter a filename", style=wx.FD_SAVE)
        if dialog.ShowModal() == wx.ID_OK:
            filename = dialog.GetPath()
        dialog.Destroy()
        pygame.image.save(self.windowSurface, filename)



#-------------------------------------------------------------------------------
# Here the creation of the main user interface window ends
# The following routines are not part of the user interface
#-------------------------------------------------------------------------------


#-------------------------------------------------------------------------------
# This routine is used for testing purposes
#-------------------------------------------------------------------------------
        
def Ontestbutton(event):
    pass
    #print 'This is the test button allright'

   
#-------------------------------------------------------------------------------
# This routine loads the URLs of all worlds from the file grepomaps.cfg
#-------------------------------------------------------------------------------

def LoadConfigData():

    global aw;aw = 0
    global world; world = []
    global url_players; url_players = []
    global url_conquers; url_conquers = []
    global url_alliances; url_alliances = []
    global url_towns; url_towns = []
    global url_islands; url_islands = []

    f = open (r"grepomaps.cfg", 'r')
    line = f.readline()
    count = int(line[9:len(line)-1])

    for w in range(0,count):
        line = f.readline()
        world.append(line[8:len(line)-1])
        line = f.readline()
        url_players.append(line[14:len(line)-1])
        line = f.readline()
        url_conquers.append(line[15:len(line)-1])
        line = f.readline()
        url_alliances.append(line[16:len(line)-1])
        line = f.readline()
        url_towns.append(line[12:len(line)-1])
        line = f.readline()
        url_islands.append(line[14:len(line)-1])
        

#-------------------------------------------------------------------------------
# The following routines transfer IDs in names and vice versa
#-------------------------------------------------------------------------------

def get_player_ID(player):
    if player in player_name:
        return player_ID[player_name.index(player)]

def get_player_name(player):
    if player in player_ID:
        return player_name[player_ID.index(player)]

def get_alliance_ID(alliance):
    if alliance in alliance_name:
        return alliance_ID[alliance_name.index(alliance)]

def get_alliance_name(alliance):
    if alliance in alliance_ID:
        return alliance_name[alliance_ID.index(alliance)]

def get_date(datestring):
    yy=datestring.GetYear()
    mm=datestring.GetMonth()+1
    dd=datestring.GetDay()
    return date(yy, mm, dd)
    
#-------------------------------------------------------------------------------
# The following routine presents the colour chooser window and returns a colour
#-------------------------------------------------------------------------------

def choose_colour():
    dialog = wx.ColourDialog(None)
    dialog.GetColourData().SetChooseFull(True)
    if dialog.ShowModal() == wx.ID_OK:
        data = dialog.GetColourData()
        color = data.GetColour().Get()
    dialog.Destroy()
    return color

def CopyToClipboard(text):
    text2=text.replace('+', ' ')
    clipdata = wx.TextDataObject()
    clipdata.SetText(text2)
    wx.TheClipboard.Open()
    wx.TheClipboard.SetData(clipdata)
    wx.TheClipboard.Close()
    
#-------------------------------------------------------------------------------
# At this point we're done with defining routines
# The actual program (application) is initiated
# 
# First the application that wxpython needs is defined
# Next the menu window is generated and presented to the user
# After that pygame is initiated
# Then the application loop is entered waiting for user generated events
#-------------------------------------------------------------------------------

app = wx.App()
Menu(None, -1, '')
pygame.init()   # initialise the pygame engine
app.MainLoop()
